package dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import bo.Conta;
import exception.DataException;
import exception.DatabaseConnectException;
import exception.EmptyResultException;

public class ContaDAO {

	private static ContaDAO inst;

	private ContaDAO() {
	}

	public static ContaDAO getInst() {

		if (inst == null) {
			inst = new ContaDAO();
		}
		return inst;
	}

	public ArrayList<Conta> consultaTodosRegistros()
			throws EmptyResultException, DataException, SQLException,
			DatabaseConnectException {
		ArrayList<Conta> contas = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			preparedStatement = Conexao
					.getInst()
					.getConnection()
					.prepareStatement(
							"SELECT "
									+ "id_conta id_cliente id_pedido "
									+ "dt_compra dt_criacao_conta valor_devedor"
									+ "valor_pago saldo"
									+ "FROM conta ORDER BY conta.id;");

			resultSet = preparedStatement.executeQuery();

			contas = new ArrayList<Conta>();

			while (resultSet.next()) {
				Conta conta = new Conta();
				conta.setIdConta(resultSet.getInt(1));
				conta.setIdCliente(resultSet.getInt(2));
				conta.setIdPedido(resultSet.getInt(3));
				conta.setDtCompra(resultSet.getDate(4));
				conta.setDtCriacaoConta(resultSet.getDate(5));
				conta.setValorDevedor(resultSet.getDouble(6));
				conta.setValorPago(resultSet.getDouble(7));
				conta.setSaldo(resultSet.getDouble(8));
				contas.add(conta);
				conta = null;
			}

			if (contas.isEmpty()) {
				throw new EmptyResultException();
			}

		} finally {
			if (preparedStatement != null) {
				preparedStatement.close();
			}
			if (resultSet != null) {
				resultSet.close();
			}
		}

		return contas;

	}

}
